<template>
  <div class="app-container">
    <CommonContainer title="用户信息">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
        <el-row>
          <el-col :span="8">
            <el-form-item label="用户姓名" prop="nickName">
              <el-input style="width: 80%" v-model="form.nickName" placeholder="请输入用户姓名" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="归属组织" prop="deptId">
              <treeselect style="width: 80%;height: 25px" v-model="form.deptId" :options="deptOptions" :defaultExpandLevel="10"
                          :show-count="true" placeholder="请选择归属组织"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input style="width: 80%" v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="邮箱" prop="email">
              <el-input style="width: 80%" v-model="form.email" placeholder="请输入邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="用户账号" prop="userName">
              <el-input style="width: 80%" v-model="form.userName" placeholder="请输入用户账号" maxlength="30"/>
            </el-form-item>
          </el-col>
          <el-col :span="8" v-if="form.userId == undefined">
            <el-form-item label="用户密码" prop="password">
              <el-input class="password-input" style="width: 80%" v-model="form.password" placeholder="请输入用户密码" type="text" maxlength="20"
                        onkeyup="value=value.replace(/[\u4E00-\u9FA5]/g,'')">
                <i slot="suffix" class="el-icon-view" @click="hiddenPwd"></i>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="用户性别">
              <el-select style="width: 80%" v-model="form.sex" placeholder="请选择性别">
                <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="角色" prop="roleIds">
              <el-select style="width: 80%" v-model="form.roleIds" multiple placeholder="请选择角色" filterable>
                <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName" :value="item.roleId"
                           :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="岗位" prop="postIds">
              <el-select style="width: 80%" v-model="form.postIds" multiple placeholder="请选择岗位" filterable>
                <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId"
                           :disabled="item.status == 1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="NC员工id" prop="ncId">
              <el-input style="width: 80%" v-model="form.ncId" placeholder="请输入NC员工id" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="NC员工编码" prop="ncCode">
              <el-input style="width: 80%" v-model="form.ncCode" placeholder="请输入NC员工编码" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="OA员工编码" prop="oaCode">
              <el-input style="width: 80%" v-model="form.oaCode" placeholder="请输入OA员工编码" maxlength="50"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="nc供应商id" prop="ncSupplierId">
              <el-input style="width: 80%" v-model="form.ncSupplierId" placeholder="请输入nc供应商id" maxlength="50"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="nc供应商code" prop="ncSupplierCode">
              <el-input style="width: 80%" v-model="form.ncSupplierCode" placeholder="请输入nc供应商code" maxlength="50"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="用户状态">
              <el-radio-group style="width: 80%" v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{
                    dict.label
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务类型" required>
              <el-radio-group style="width: 80%" v-model="form.businessType">
                <el-radio v-for="dict in dict.type.user_business_type" :key="dict.value" :label="dict.value">{{dict.label}}</el-radio>
              </el-radio-group>

            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="岗位状态" required>
              <el-radio-group style="width: 80%" v-model="form.workingCondition">
                <el-radio label="1">在岗</el-radio>
                <el-radio label="2">离岗</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </CommonContainer>
    <div class="card-wrap flex justify-end card-padding">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">保 存</el-button>
    </div>
  </div>
</template>

<script>
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {addUser, deptTreeSelect, updateUser, getUser, getUserUpdate} from "@/api/system/user";

export default {
  name: 'UserAdd',
  dicts: ['sys_normal_disable', 'sys_user_sex', 'user_business_type'],
  components: {Treeselect},
  props: {},
  data() {
    // 密码校验 长度不能小于8位且不能大于20位字符,必须包含大写字母、小写字母、数字和特殊符号
    const ISPWD = /^(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*,\._\+(){}])[0-9a-zA-Z!@#$%^&*,\\._\+(){}]{8,20}$/;
    // 密码校验
    const validatePassword = (rule, value, callback) => {
      if (!ISPWD.test(this.form.password)) {
        callback(new Error("用户密码必须包含大写字母、小写字母、数字和特殊符号"));
      } else {
        callback();
      }
    };
    return {
      // 组织树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 组织名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      form: {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: "0",
        remark: undefined,
        postIds: [],
        roleIds: [],
        businessType: '1',
        workingCondition: '1',
        ncName:null,//ncName
        ncId:null,//ncId
        ncCode:null,//nc编码
        oaCode:null,//oa编码
        ncSupplierId:null,//
        ncSupplierCode:null,//
      },
      // 表单校验
      rules: {
        userName: [
          {required: true, message: "用户账号不能为空", trigger: "blur"},
          {min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur'}
        ],
        nickName: [
          {required: true, message: "用户姓名不能为空", trigger: "blur"}
        ],
        deptId: [
          {
            required: true,
            message: "请选择归属组织",
            trigger: ["blur", "change"]
          }
        ],

        password: [
          {required: true, message: "用户密码不能为空", trigger: "blur"},
          {min: 8, max: 20, message: '用户密码长度必须介于 8 和 20 之间', trigger: 'blur'},
          {required: true, validator: validatePassword, trigger: 'blur'}
        ],
        email: [
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phonenumber: [
          {
            required: true,
            message: "请输入手机号码",
            trigger: ["blur"]
          },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        postIds: [
          {
            required: true,
            message: "请选择岗位",
            trigger: ["blur", "change"]
          }
        ],
        roleIds: [
          {
            required: true,
            message: "请选择角色",
            trigger: ["blur", "change"]
          }
        ],
      },
      showPwd:false,
    }
  },
  computed: {},
  watch: {
    // 根据名称筛选组织树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {

    //获取默认信息
    getInitInfo() {
      getUser().then(response => {
        this.postOptions = response.data.posts;
        this.roleOptions = response.data.roles;
      });
    },
    getUserInfo() {
      getUserUpdate(this.form.userId).then(response => {
        this.form = response.data.user;
        this.postOptions = response.data.posts;
        this.roleOptions = response.data.roles;
        this.$set(this.form, "postIds", response.data.postIds);
        this.$set(this.form, "roleIds", response.data.roleIds);
      });
    },

    /** 查询组织下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.userId != undefined) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.cancel()
            });
          } else {
            addUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.cancel()
            });
          }
        }
      });
    },
    hiddenPwd() {
      this.showPwd = !this.showPwd // 默认为false
      if (this.showPwd) {
        document.getElementsByClassName('password-input')[0].style.webkitTextSecurity = 'none'
      } else {
        document.getElementsByClassName('password-input')[0].style.webkitTextSecurity = 'disc'
      }
    },
    // 取消按钮
    cancel() {
      this.$router.back()
      this.$store.dispatch('tagsView/delView', this.$route)
    },
  },
  created() {
    this.getDeptTree();

  },
  mounted() {
    if (this.$route.query.userId) {
      this.form.userId = this.$route.query.userId
      this.getUserInfo()
    } else {
      this.getConfigKey("sys.user.initPassword").then(response => {
        this.initPassword = response.msg;
        this.getInitInfo();
      });
    }
  },

}
</script>

<style lang="scss" scoped>
::v-deep .el-form .el-form-item__content:has(.el-radio-group, .el-date-editor, .el-input, .el-checkbox .vue-treeselect) {
  line-height: 32px;
  height: 32px;
}
.password-input {
  position: relative;
  font-size: 14px; /* 调整字体大小以适配隐藏文本 */
  color: transparent; /* 将文本颜色设为透明 */
  letter-spacing: 0.25em; /* 调整字符间距以隐藏文本 */
  -webkit-text-security: disc; /* 将输入内容显示为圆点，适用于部分浏览器 */
}
::v-deep .el-input__suffix {
  right: 7px;
  -webkit-text-security: none !important;
}
</style>
